package com.zxj.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zxj.common.core.contains.CacheConstants;
import com.zxj.common.redis.service.RedisService;
import com.zxj.friend.domain.user.entity.User;
import com.zxj.friend.domain.user.vo.UserVO;
import com.zxj.friend.mapper.user.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class UserCacheManager {

    private final RedisService redisService;

    private final UserMapper userMapper;

    /**
     * 从缓存中获取用户信息, 如果缓存不存在会从数据库中查询并放入缓存
     * @param userId 用户id
     * @return 用户信息
     */
    public UserVO getUserById(Long userId) {
        // 1. 获取缓存 key
        String userKey = getUserKey(userId);
        UserVO userVO = redisService.getCacheObject(userKey, UserVO.class);
        if (userVO != null) {
            //缓存存在并, 将缓存延长10min后返回
            redisService.expire(userKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
            return userVO;
        }
        // 2. 缓存不存在, 从数据库中查询
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .select(User::getUserId,
                        User::getNickName,
                        User::getHeadImage,
                        User::getSex,
                        User::getEmail,
                        User::getPhone,
                        User::getWechat,
                        User::getIntroduce,
                        User::getSchoolName,
                        User::getMajorName,
                        User::getStatus)
                .eq(User::getUserId, userId));
        if (user == null) {
            // 3. 数据库中不存在该用户
            return null;
        }
        // 4. 刷新用户缓存
        refreshUser(user);
        // 5. 构造返回对象
        userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    public void refreshUser(User user) {
        //刷新用户缓存
        String userKey = getUserKey(user.getUserId());
        redisService.setCacheObject(userKey, user);
        //设置用户缓存有效期为10分钟
        redisService.expire(userKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }

    //u:d:用户id
    private String getUserKey(Long userId) {
        return CacheConstants.USER_DETAIL + userId;
    }
}
